package cn.admin.config.common.protocol;

import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SwizzleEncoder extends AbstractSerializer {

    @Override
    public void writeObject(Object swizzle, AbstractHessianOutput out) throws IOException {
        if (!out.addRef(swizzle)) {
            Object object;
            byte[] bytes;
            try {
                object = SwizzleCodec.f_object.get(swizzle);
                bytes = (byte[]) SwizzleCodec.f_bytes.get(swizzle);
            } catch (IllegalAccessException e) {
                throw new IOException(e);
            }

            if (bytes == null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                try (ObjectOutputStream javaos = new ObjectOutputStream(bos)) {
                    javaos.writeObject(object);
                }
                bytes = bos.toByteArray();
            }

            out.writeMapBegin(Swizzle.class.getName());
            out.writeString("serialization");
            out.writeInt(1);
            out.writeString("bytes");
            out.writeBytes(bytes);
            out.writeMapEnd();
        }
    }
}
